package cn.yh.register.msm.api;

import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.result.Result;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.common.util.RandomUtil;
import cn.yh.register.msm.service.MsmService;
import com.alibaba.excel.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送服务")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    MsmService msmService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @ApiOperation("发送验证码")
    @GetMapping("/send/{phone}")
    public Result<?> send (@PathVariable String phone){
        //如果验证码没失效，直接返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //生成验证码
        code = RandomUtil.getSixBitRandom();
        if (msmService.send(phone,code)) {
            //发送成功设置过期时间1分钟
            redisTemplate.opsForValue().set(phone,code,30, TimeUnit.MINUTES);
            String s = redisTemplate.opsForValue().get(phone);
            System.out.println(s);
            return Result.ok();
        }else {
            return Result.fail().message("发送失败");
        }
    }
}
